package com.zyw.zhuangdian.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zyw.zhuangdian.service.CacheService;
import com.zyw.zhuangdian.util.BeanConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class CacheServiceImpl implements CacheService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";

    public void setKeyValue(String key,String value){
        ValueOperations<String,String> valueOperations = redisTemplate.opsForValue();
        valueOperations.set(key,value);
    }

    public void setKeyObject(String key,Object value){
        ValueOperations<String,String> valueOperations = redisTemplate.opsForValue();
        valueOperations.set(key, JSON.toJSONStringWithDateFormat(value,dateFormat));
    }

    public void setKeyValueExpire(String key, String value,Long timeOut) {
        ValueOperations<String,String> valueOperations = redisTemplate.opsForValue();
        valueOperations.set(key, value,timeOut, TimeUnit.MINUTES);
    }

    public void setKeyObjectExpire(String key, Object value,Long timeOut) {
        ValueOperations<String,String> valueOperations = redisTemplate.opsForValue();
        valueOperations.set(key, JSON.toJSONStringWithDateFormat(value,dateFormat),timeOut, TimeUnit.MINUTES);
    }

    public <T> T getKey(String key, Class<T> clazz){
        ValueOperations<String,String> valueOperations = redisTemplate.opsForValue();
        String res = valueOperations.get(key);
        JSONObject json = JSON.parseObject(res);
        return BeanConvertUtil.covertBean(json,clazz);
    }
    public String getKey(String key){
        ValueOperations<String,String> valueOperations = redisTemplate.opsForValue();
        return valueOperations.get(key);
    }
    public Boolean hasKey(String key){
        return redisTemplate.hasKey(key);
    }
    public Set<String> findKeys(String pattern){
        return redisTemplate.keys(pattern);
    }

    @Override
    public void delKey(String key) {
        redisTemplate.delete(key);
    }
}
